﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using ICSharpCode.SharpZipLib.Zip;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("order"),JwtAuthActionFilter]
    public class OrderController : PageController
    {

        // PUT: api/Order/5
        /// <summary>
        /// 改变已有订单号的状态  并删除文件夹
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut]
        public HttpResponseMessage Put(dynamic obj)
        {
            SQLCommand sc = null;
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "参数不能为空" });
            else
            {
                int id = Convert.ToInt32(obj.Id);
                string ordername = obj.OrderId.ToString();
                try
                {
                    string sql = "update Order_tb set state=0 where id=" + id;
                    sc = new SQLCommand(sql);
                    int res = sc.ExecuteNonQuery();
                    if (res == 1)
                    {
                        WriteDebug("DelePC", "成功废弃订单 "+id);
                        string path = GetPCPath(ordername);
                        if (Directory.Exists(path))
                        {
                            DeleteFolder(path);
                            Directory.Delete(path);
                        }                        
                        return DelePC(id);
                    }else
                        return AssistFun.toJson(new { status = 201, tip = "失败" }); 
                }
                catch (Exception e)
                {
                    sc = new SQLCommand("update Order_tb set state=1 where id=" + id);
                    sc.ExecuteNonQuery();
                    WriteDebug("ChangeOrderStateDelDir", e.Message);
                    return AssistFun.toJson(new { status = 201, tip = "失败" }); ;
                }
            }
        }

        /// <summary>
        /// 删除订单对应的流程 以及pod 真删
        /// </summary>
        /// <param name="Orderid"></param>
        private HttpResponseMessage DelePC(int Orderid)
        {
            List<SQLCommand> cmds = new List<SQLCommand>();
            try
            {
                string sql = "delete PC_tb where pc_id=@pcid";
                SQLCommand sc = new SQLCommand(sql, "@pcid", Orderid);
                cmds.Add(sc);
                sql = "delete Pod_tb where order_id=@orderid";
                sc = new SQLCommand(sql, "@orderid", Orderid);
                sql = "delete LSH_tb where order_id=@orderid";
                sc = new SQLCommand(sql, "@orderid", Orderid);
                cmds.Add(sc);
                SQLCommand.ExecTran(cmds);
                WriteDebug("DelePC", "成功删除订单对应的流程 以及pod ");
                return AssistFun.toJson(new { status = 200, tip = "成功"});
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new {status=201,tip=e.Message });
            }            
        }

        #region  生产单查询
        //生产单查询  
        [HttpGet, Route("orderSearch")]
        public HttpResponseMessage SelectProductOrder(int page = 1, int limit = 10, string ModelName = null, string OrderId = null, string ErpName = null, DateTime? sTime = null, DateTime? eTime = null, int Yield = -1, string State = "1", string IsBind = null)
        {
            int loginid = GetCrrentIDByToken();
            if (loginid == 0)
                return AssistFun.toJson(new { status = 201, tip = "工号不存在", data = "" });
            User user = GetUserByLoginID(loginid);
            try
            {
                string fields = "(select count(*) from Pod_tb where Pod_tb.order_id = Order_tb.id) as Pod,(select count(*) from Bed_tb where Bed_tb.order_id=Order_tb.id) as Bed, Order_tb.id as Id, Order_tb.name as OrderId,Model_tb.name as ModelName,erp_name as ErpName,creater_time as Time,quantity as Yield,Order_tb.state as State,o_model_id as ModelId,Order_tb.bind_id as BindId,PL_tb.type as type ";
                string table = "Order_tb join Model_tb on  Order_tb.o_model_id=Model_tb.id join PL_tb on order_tb.o_PLID=PL_tb.id";
                string where = PingJieCmdForOrder(user.PLID, ModelName, OrderId, ErpName, sTime, eTime, Yield, State, IsBind);
                int totalPage, totals;
                string order = " Order_tb.creater_time desc";
                if (Convert.ToInt32(IsBind) != 0)
                    order = " Order_tb.bind_id desc";
                //DataTable dt = SQLCommand.GetDataListByPage(table, fields, order, where, limit, page, out totalPage, out totals);
                DataTable dt = null;
                SQLCommand.GetDataListByPage(table, fields, order, where, limit, page, out totalPage, out totals,out dt);
                if (dt == null)
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有生产单信息", data = "" });
                else
                {

                    if (IsOracle)
                    {
                        List<OrcProductInfo> producs =  AssistFun.DataTableToList<OrcProductInfo>(dt);
                        return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totals, rows = producs } });
                    }
                    else
                    {
                        List<SqlProductInfo> producs =  AssistFun.DataTableToList<SqlProductInfo>(dt);
                        return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totals, rows = producs } });
                    }                    
                }
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }
        }

        private string PingJieCmdForOrder(int plid, string modelname, string OrderId, string brand = null, DateTime? sTime = null, DateTime? eTime = null, int yield = -1, string State = null, string IsBind = null)
        {
            string sql = "";
            if (plid.ToString()!=null&&plid > 0)
            {
                sql += " and Order_tb.o_PLID=" + plid;
            }
            if (modelname != null)
                sql += string.Format(" and Model_tb.name like '%{0}%' ", modelname);
            if (OrderId != null)
                sql += string.Format(" and Order_tb.name like '%{0}%'", OrderId);
            if (brand != null)
                sql += string.Format(" and erp_name like '%{0}%'", brand);
            if (sTime != null)
                sql += " and creater_time>='" + sTime + "'";
            if (eTime != null)
                sql += " and creater_time<='" + eTime + "'";
            if (yield.ToString()!=null&&yield > 0)
            {
                sql += " and quantity>=" + yield;
            }
            if (State != null)
            {
                if (Convert.ToInt32(State) == 1)
                {
                    if (IsOracle)
                        sql += " and to_char(finish_time,'yyyy-mm-dd hh24:mi:ss')>to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') and Order_tb.state=1";
                    else
                        sql += " and GETDATE()<finish_time and Order_tb.state=1";
                }
                if (Convert.ToInt32(State) == 3)
                {
                    if (IsOracle)
                        sql += " and to_char(finish_time,'yyyy-mm-dd hh24:mi:ss')<to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') and Order_tb.state=1";
                    else
                        sql += " and GETDATE()>finish_time and Order_tb.state=1";
                }
                if (Convert.ToInt32(State) == 0)
                    sql += " and Order_tb.state=0";
                if (Convert.ToInt32(State) == 2)
                    sql += " and Order_tb.state=2";
            }
            if (IsBind != null)
            {
                if (Convert.ToInt32(IsBind) == 0)
                {
                    //sql += sql + " and Order_tb.bind_id=0";
                }
                else
                {
                    sql += sql + "and Order_tb.bind_id !=0";
                }
            }
            return sql;
        }

        #endregion
            
        #region 生产单绑定
        [HttpPut, Route("binding")]
        public HttpResponseMessage Binding(string[] orderId)
        {
            //多个生产单邦定的话, 其中有一个是主生产单,其bind_id = id,其他生产单的bind_id = 主生产单的id
            SQLCommand sc = null;
            if (orderId.Length > 1)
            {
                string sql = "";
                int count = 0;
                int first = 0;
                int nums = 0;
                List<SQLCommand> cmds = new List<SQLCommand>();
                for (int i = 0; i < orderId.Length; i++)
                {
                    sql = string.Format("SELECT state, bind_id, o_model_id FROM Order_tb where id ='{0}'", orderId[i]);
                    sc = new SQLCommand(sql);
                    DataTable bind = sc.ExecuteScalars();
                    if (bind == null)
                        return AssistFun.toJson(new RespondModel(201, "没有找到所选生产单"));

                    int state = Int32.Parse((bind.Rows[0][0]).ToString());
                    int bind_id = Int32.Parse((bind.Rows[0][1]).ToString());
                    int model_id = Int32.Parse((bind.Rows[0][2]).ToString());
                    if (state == 1)
                    {
                        if (bind_id == 0)
                        {
                            //是否所有订单的model_id相同
                            if (model_id == first || i == 0)
                            {
                                first = model_id;
                            }
                            else
                            {
                                //是否所有订单的人数相同
                                sql = "select count(*) from LSH_tb where order_id='" + orderId[i] + "'";
                                sc = new SQLCommand(sql);
                                int num = int.Parse(sc.ExecuteScalar());
                                if (num == nums || i == 0)
                                {
                                    nums = num;
                                }
                                else
                                    return AssistFun.toJson(new RespondModel(201, "所选生产单不符合绑定条件"));
                            }
                        }
                        else
                            return AssistFun.toJson(new RespondModel(201, "所选对象已经绑定"));
                    }
                    else
                        return AssistFun.toJson(new RespondModel(201, "所选对象已经废弃或已完成"));

                    sc = new SQLCommand("UPDATE Order_tb SET bind_id=@bindid WHERE id=@id");
                    sc.Add("@bindid", orderId[0]);
                    sc.Add("@id", orderId[i]);
                    cmds.Add(sc);

                    sc = new SQLCommand("UPDATE PC_tb SET bind_id=@bindid WHERE pc_id=@id");
                    sc.Add("@bindid", orderId[0]);
                    sc.Add("@id", orderId[i]);
                    cmds.Add(sc);
                }

                count = SQLCommand.ExecTran(cmds);
                if (count > 0)
                {
                    return AssistFun.toJson(new RespondModel(200, "修改成功"));
                }
                else
                {
                    return AssistFun.toJson(new RespondModel(201, "修改失败"));
                }
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "缺少绑定对象"));
            }

        }
        #endregion    

        #region 生产单解除绑定
        [HttpPut, Route("removebinding")]
        public HttpResponseMessage RemoveBinding(string[] bindId)
        {
            int count = 0;
            List<SQLCommand> cmds = new List<SQLCommand>();
            SQLCommand sc = null;
            for (int i = 0; i < bindId.Length; i++)
            {
                if (Convert.ToInt32(bindId[i]) != 0)
                {
                    sc = new SQLCommand("UPDATE Order_tb SET bind_id=0 WHERE bind_id=@bindid", "@bindid", bindId[i]);
                    cmds.Add(sc);
                    sc = new SQLCommand("UPDATE PC_tb SET bind_id=0 WHERE bind_id=@bindid", "@bindid", bindId[i]);
                    cmds.Add(sc);
                }
                else
                {
                    return AssistFun.toJson(new RespondModel(201, "选定对象未绑定"));
                }
            }

            count = SQLCommand.ExecTran(cmds);
            if (count > 0)
            {
                return AssistFun.toJson(new RespondModel(200, "修改成功"));
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
            }
        }
        #endregion

        #region 生产单下载
        /// <summary>
        /// 生产单文件打包下载 
        /// </summary>  
        /// <param name="Id"></param>
        /// <returns></returns> 
        [HttpGet, Route("downOrder")]
        public HttpResponseMessage DownOrder(int Id, string token)
        {
            try
            {
                WriteDebug("DownOrder", "进入生产单下载，ID：" + Id);
                int loginid = GetCrrentIDByToken(token);
                if (loginid == 0)
                    return AssistFun.toJson(new { status = 201, tip = "你无权下载" });

                string sql = "select name,state from Order_tb where id=@id";
                SQLCommand sc = new SQLCommand(sql,"@id",Id);
                DataRow dr = sc.ExecuteOneRow();
                if (dr == null)
                    return AssistFun.toJson(new { status = 201, tip = "不存在该生产单信息" });
                else
                {
                    string orderName = dr["name"].ToString();
                    int state = Convert.ToInt32(dr["state"]);
                    string orderPath = "";
                    if (state == 1)
                        orderPath = GetPCPath(orderName);
                    if (state == 2)
                        orderPath = GetHistoryPath(Id)+ "\\" + orderName;  
                    WriteDebug("DownOrder", "生产单下载路径：" + orderPath);
                    string TartgetFile = orderPath.Substring(0, orderPath.LastIndexOf(@"\")) + "\\" + orderName + ".zip";
                    using (ZipOutputStream ComStream = new ZipOutputStream(File.Create(TartgetFile)))
                    {
                        ComStream.SetLevel(6);      //压缩等级
                        if (!Directory.Exists(orderPath))
                            return AssistFun.toJson(new { status = 201, tip = "不存在生产单" + orderName + "的目录" });
                        //压缩文件 有同名压缩文件会自动替换                    
                        ZipFloder(orderPath, ComStream, orderPath);
                    }
                    //成功压缩  下载文件 
                    return Download(TartgetFile);
                }
               
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message });
            }
        }


        #endregion 

    }
}
